﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CodeGenerator.Model
{
    public abstract class doc
    {
        public doc() { }

        public string headTitle { get; private set; }
        public string headName { get; private set; }
        public string tblName{ get; private set;}

        public int fieldNum { get; private set; }
        public string txtlist { set; get; }
        public string fnameList { set; get; }
        public string[] txts { get; private set; }
        public string[] fnames { get; private set; }
        public string[] tys { get; private set; }

        public string[] tyDb { get; private set; }
        public string[] tyProgram { get; private set; }

        public bool statusOk = false;
        public string errorMessage="";

        /// <summary>
        /// 把输入的简略类型标识转换成数据库和程序语言的类型名
        /// </summary>
        /// <returns></returns>
        private bool initTyps()
        {
            if (fieldNum < 1)
            {
                errorMessage = "类型格式为零。";
                return false;
            }

            //tys.CopyTo(tyDb,0);
            //tys.CopyTo(tyProgram,0);
            tyDb = (string[])tys.Clone();
            tyProgram = (string[])tys.Clone();

            for (int i = 0; i < fieldNum; i++)
            {
                string s = tys[i];
                int sl = 0;
                if(s.Substring(0,1)=="c")sl=int.Parse(s.Replace("c",""));
                switch (s.Substring(0,1))
                {
                    #region 类型转换
                    case "i":
                        tyDb[i] = "int";
                        tyProgram[i] = "Int32";
                        break;
                    case "f":
                        tyDb[i] = "float";
                        tyProgram[i] = "float";
                        break;
                    case "m":
                        tyDb[i] = "decimal";
                        tyProgram[i] = "decimal";
                        break;
                    case "t":
                        tyDb[i] = "text";
                        tyProgram[i] = "string";
                        break;
                    case "c":
                        tyDb[i] = "varchar(" + sl.ToString() + ")";
                        tyProgram[i] = "string";
                        break;
                    case "d":
                        tyDb[i] = "datetime";
                        tyProgram[i] = "DateTime";
                        break;
                    default:
                        tyDb[i] = "varchar(100)";
                        tyProgram[i] = "string";
                        break; 
                    #endregion
                }
            }

            return true;
        }

        /// <summary>
        /// 把输入数据初始化为文档
        /// </summary>
        /// <param name="content"></param>
        public doc(string content)
        {
            #region 格式化和检查数据
            content = content.Replace('，', ',');
            string[] rows = content.Split('\r');
            //msg = rows.Length.ToString() + " rows\r";

            if (rows.Length != 4)
            {
                errorMessage = "文档行数不对，应该是4行数据。";
                return;
            }

            string[] heads = rows[0].Split(',');
            if (heads.Length != 2)
            {
                errorMessage = "表头不对。";
                return;
            }

            headName = heads[1];
            headTitle = heads[0];

            txtlist = rows[1].Trim();
            fnameList = rows[2].Trim();
            txts = txtlist.Split(',');
            fnames = fnameList.Split(',');
            tys = rows[3].Split(',');
            fieldNum = txts.Length;

            if (txts.Length != fnames.Length || fnames.Length != tys.Length)
            {
                errorMessage = string.Format("数据列数不对。{0},{1},{2}", txts.Length, fnames.Length, tys.Length);
                return;
            }

            
            if (!initTyps()) return; 
            #endregion

            statusOk = true;
 
        }

        public string createMsSql(string prefix="BZZ_")
        {
            StringBuilder sb = new StringBuilder();
            tblName = prefix + headName;
            sb.Append("--------------------------\r\n");
            sb.Append("-- 创建表[" + headTitle + " ]开始: \r\n");
            sb.Append("-- alter table  [" + tblName + " ] add\r\n");
            sb.Append("-- IF EXISTS (SELECT 1 FROM sysobjects WHERE xtype='u' AND name='" + tblName + "') drop table " + tblName + "\r\n");
            sb.Append("  CREATE TABLE [" + tblName + "] (\r\n");
            if (fnames[0] == "id")
            {
                sb.Append("	 [id] integer IDENTITY (1, 1) PRIMARY KEY NOT NULL ,\r\n");
            }
            for (int i = 1; i < fieldNum; i++)
            {
                sb.Append("	 ["+fnames[i]+"] "+tyDb[i]);
                if (i < fieldNum - 1) sb.Append(",\r\n");
            }
            sb.Append("\r\n  )\r\n");
            sb.Append("\r\n");
            sb.Append(" exec sp_addextendedproperty N'MS_Description',N'" + headTitle + " ',N'user',N'dbo',N'table',N'" + tblName + "', NULL, NULL\r\n");

            for (int i = 1; i < fieldNum; i++)
            {
                sb.Append(" exec sp_addextendedproperty N'MS_Description',N'" + fnames[i] + " ',N'user',N'dbo',N'table',N'" + tblName + "',N'column',N'" + txts[i] + " '\r\n");
            }

            sb.Append("");

            return sb.ToString();
        }

        /// <summary>
        /// 首字母大写
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public string toTitle(string s)
        {
            return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s);
        }
    }
}
